package com.dao;

import com.bean.User;
import com.utils.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    /**
     * 登录的方法
     * @param username
     * @param password
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public User login(String username, String password) throws SQLException, ClassNotFoundException {
        String sql = "select user_id, user_username, user_password, user_gender, user_email from users where user_username = ? and user_password = ?";
        System.out.println("要执行的语句是：" + sql);

        // 创建连接对象
        try (Connection connection = DBHelper.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)){
            statement.setString(1, username);
            statement.setString(2, password);
            try (ResultSet rs = statement.executeQuery()){
                // 因为查询出来只有一条记录，所以用 if
                if (rs.next()) {
                    User user = new User();
                    user.setId(rs.getInt(1));
                    user.setUsername(rs.getString(2));
                    user.setPassword(rs.getString(3));
                    user.setGender(rs.getString(4));
                    user.setEmail(rs.getString(5));
                    return user;
                } else {
                    return null;
                }
            }
        }
    }

    /**
     * 注册的方法
     * @param user
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public void insert(User user) throws SQLException, ClassNotFoundException {
        String sql = "insert into users (user_username, user_password, user_gender, user_email) values (?, ?, ?, ?)";
        System.out.println("要执行的语句是：" + sql);

        // 创建连接对象
        try (Connection connection = DBHelper.getConnection();
            PreparedStatement statement = connection.prepareStatement(sql)){
            statement.setString(1, user.getUsername());
            statement.setString(2, user.getPassword());
            statement.setString(3, user.getGender());
            statement.setString(4, user.getEmail());
            statement.executeUpdate();
        }
    }

    // 测试方法
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        System.out.println(new UserDao().login("admin", "11111"));
        System.out.println("登录成功");
    }
}
